﻿/*
 * @Description:wx第三方平台
 * @Author: maskMan
 * @LastEditTime: 2024-01-26 13:11:15
 */

import { util } from "./util";
import { conf } from "./config";
import { H5Parm, Obj } from "./type";
import Request from "./request";
export default class Platform {
  private static _wxToken = { token: null, time: 0 };
  private static async _getH5VerifyData(h5: H5Parm): Promise<any> {
    try {
      const data = {
        access_token: this._wxToken.token,
        type: "jsapi",
      };
      const res = await Request.get("/cgi-bin/ticket/getticket", data);
      if (res) {
        const { code, state } = h5;
        const ret = {
          page: `${conf.url}?code=${code}&state=${state}`,
          appid: conf.appid,
          timeStamp: util.now().toString(),
          ticket: res.ticket,
          nonceStr: util.formaDate(2),
          signature: "",
        };
        const str = "jsapi_ticket=" + ret.ticket + "&noncestr=" + ret.nonceStr + "&timestamp=" + ret.timeStamp + "&url=" + ret.page;
        ret.signature = util.md5("SHA1", str);
        return ret;
      }
      return null;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  /**微信公众号H5获取用户信息
   *  @param  code 微信密匙
   */
  public static async getH5UserInfo(code: string): Promise<Obj> {
    const data = {
      appid: conf.appid,
      secret: conf.secret,
      code: code,
      grant_type: "authorization_code",
    };
    const res = await Request.get("/sns/oauth2/access_token", data);
    if (res) {
      const { openid, access_token } = res;
      if (openid && access_token) {
        const sd = {
          access_token: access_token,
          openid: openid,
          lang: "zh_CN",
        };
        return await Request.get("/sns/userinfo", sd);
      }
    }
    return null;
  }
  /**获取微信返回验证信息*/
  public static async getH5ResData(h5Data: H5Parm): Promise<any> {
    if (!this._wxToken.token || (this._wxToken.token && util.now(true) - this._wxToken.time > 7000)) {
      const data = {
        grant_type: "client_credential",
        appid: conf.appid,
        secret: conf.secret,
      };
      const res = await Request.get("/cgi-bin/token", data);
      if (res) {
        const { access_token } = res;
        if (access_token) {
          this._wxToken.token = access_token;
          this._wxToken.time = util.now(true);
          return this._getH5VerifyData(h5Data);
        }
      }
      return null;
    }
    return this._getH5VerifyData(h5Data);
  }
}
